package com.app.art.security;

import cn.hutool.json.JSONUtil;
import com.atom.module.common.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义无权限访问的返回结果
 * 当 已认证用户（authenticated）尝试访问其无权访问的资源 时，处理“权限拒绝”异常。
 * AuthenticationEntryPoint → 没登录（401）
 * AccessDeniedHandler → 登录了但没权限（403）
 */
@Slf4j
@Component
public class AccessDeniedHandler implements org.springframework.security.web.access.AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        log.info("AccessDeniedHandler >> {}  ",request.getRequestURI());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(Result.error(accessDeniedException.getMessage())));
        response.getWriter().flush();
    }
}
